package com.kanas.webak.config.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.inject.Singleton;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kanas.framework.business.BusinessException;
import com.kanas.webak.config.domain.DictType;
import com.kanas.webak.config.domain.DictValue;
import com.kanas.webak.config.repository.DictTypeRepository;
import com.kanas.webak.config.repository.DictValueRepository;

@Service("com.kanas.webak.config.service.dicttypeservice")
@Singleton
public class DictTypeServiceImpl implements  DictTypeService{
	
	@Autowired
	private DictTypeRepository dictTypeRepository;
	@Autowired
	private DictValueRepository dictValueRepository;
	
	@Override
	@Transactional
	public String addNew(DictType dt) throws Exception {
		DictType dict = dictTypeRepository.findOne(dt.getId());
		if(dict!=null)throw BusinessException.DATA_DUPLICATION;
		dictTypeRepository.save(dt);
		return dt.getId();
	}
	
	@Override
	@Transactional
	public String update(DictType dt) throws Exception {
		DictType dict = dictTypeRepository.findOne(dt.getOldId());
		if(dict==null)throw BusinessException.DATA_NOT_FOUND;
		dict.setLabel(dt.getLabel());
		dict.setTypeCode(dt.getTypeCode());
		dictTypeRepository.save(dict);
		return dt.getOldId();
	}
	
	@Override
	@Transactional
	public DictType findOne(String id) {
		DictType dt = dictTypeRepository.findOne(id);
		return dt;
	}
	
	@Override
	@Transactional
	public String remove(String did) {
		dictTypeRepository.delete(did);
		return did;
	}
	
	@Override
	@SuppressWarnings("unchecked")
	@Transactional
	public List<DictType> findAll() {
		Iterator<DictType> dts = dictTypeRepository.findAll().iterator();
		return toList(dts);
	}
	
	@Override
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List toList(Iterator its) {
		List list = new ArrayList();
		while(its.hasNext()) {
			list.add(its.next());
		}
		return list;
	}

	@Override
	public List<DictValue> findByTypeCode(String typeCode) {
		List<DictValue> dvs = new ArrayList<DictValue>();
		DictType dt = dictTypeRepository.findByTypeCode(typeCode);
		if(dt != null) dvs = dictValueRepository.findByDictType(dt);
		return dvs;
	}

	public DictTypeRepository getDictTypeRepository() {
		return dictTypeRepository;
	}

	public void setDictTypeRepository(DictTypeRepository dictTypeRepository) {
		this.dictTypeRepository = dictTypeRepository;
	}

	public DictValueRepository getDictValueRepository() {
		return dictValueRepository;
	}

	public void setDictValueRepository(DictValueRepository dictValueRepository) {
		this.dictValueRepository = dictValueRepository;
	}

}
